package com.wbs.shop.nuby.helper;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.view.OrientationEventListener;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.qlmy.cn.utils.Logger;
import com.wbs.shop.nuby.utils.Utils;

public class OrientationEventLifecycle extends OrientationEventListener implements DefaultLifecycleObserver {
    public static void orientationEventListener(LifecycleOwner owner, Activity context) {
        if (Utils.isPad() && owner != null) {
            owner.getLifecycle().addObserver(new OrientationEventLifecycle(context));
        }
    }

    private Activity mContext;

    private OrientationEventLifecycle(Activity context) {
        super(context);
        mContext = context;
        if (canDetectOrientation()) {
            enable();
        } else {
            disable();
        }
    }

    @Override
    public void onOrientationChanged(int orientation) {
        if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
        Integer newOrientation = null;
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        if (orientation > 350 || orientation < 10) { //0度
            newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        } else if (orientation > 80 && orientation < 100) { //90度
            newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        } else if (orientation > 170 && orientation < 190) { //180度
            newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        } else if (orientation > 260 && orientation < 280) { //270度
            newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        }
        if (newOrientation != null && mContext.getRequestedOrientation() != newOrientation) {
            Logger.e("orientation==>" + newOrientation);
            mContext.setRequestedOrientation(newOrientation);
        }
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        disable();
        mContext = null;
    }
}
